import Taro, { Component } from '@tarojs/taro'
// 引入组件
import { View, Image, ScrollView,Text,Button } from '@tarojs/components';
import { AtAvatar} from 'taro-ui'
import { connect } from '@tarojs/redux'
import "taro-ui/dist/weapp/components/swipe-action/index.scss";
import './show.styl'
import {GoodItem} from '../../components/homeGoodItem/goodItem'
import {asyncCancelGroup, asyncJoinGroup} from "../../api/group";
import homeImg from '../../assets/images/home.png'
import {jumpUrl} from "../../utils/router";
import NumberInput  from '../../components/NumberInput/index'
import {
    asyncLoadOffer // 加载推荐商品列表
} from '../../actions/cart'

import {
  asyncgroupDetail,asyncGoodDetailInfo// 加载拼单详情
} from '../../actions/good'
import LoginModal from '../../components/loginModal'
import { asyncGetOpenId } from '../../api/user'
import QQMapWX from '../../components/lbs/qqmap-wx-jssdk'
import { asyncGetRecommendedShop } from '../../api/shop'

let qqmapsdk
@connect(({ cart, shop ,good, user}) => ({
    cart, shop, good, user
  }), (dispatch) => ({
    // 加载商品详情
    onAsyncDetail () {
      dispatch(asyncGoodDetailInfo())
    },
    // 加载推荐商品列表
    onAsyncLoadOffer() {
      // console.log('dispatch 加载推荐商品')
      dispatch(asyncLoadOffer())
    },
    onYncgroupDetail(scenevalue) {
      dispatch(asyncgroupDetail(scenevalue))
    }
  }))
  
class Show extends Component {
    constructor () {
      super(...arguments)
      this.state = {
        num: 1,
        showAuthModal: false// 授权弹窗
      }
    }
    config = {
        navigationBarTitleText: '参与拼团',
        usingComponents: {
            'poster': '../../components/poster/poster/index',
            'count-down': '../../components/count-down/count-down'
        }
    }
    // 计数器的数量变化
    handleNumChange (value) {
      this.setState({
        num: value
      })
    }
    // 跳转
    jumpTo (url) {
        jumpUrl(url, {method: 'navigateTo'})
    }
    // 回首页
    goHome () {
      Taro.switchTab({url: '/pages/index/index'})
    }
   
  // 处理授权结果
  prcoessAuthResult(user) {
    this.setState({ showAuthModal: false })
    const { avatarUrl: avatar, nickName: nickname } = user.userInfo
    const { location } = user
    this.props.onGetWxUserInfo({ avatar, nickname }) // 设置到redux中供后续使用
    // 发送注册登录请求
    asyncGetOpenId(user.code, user.location.latitude, user.location.longitude, avatar, nickname).then(({ data, status }) => {
      if (status) {
        const { token, openid } = data
        Taro.setStorageSync('token', token)
        Taro.setStorageSync('openid', openid)
        Taro.setStorageSync('userInfo', user.userInfo)
        this.props.onGetWxUserInfo({ token, openid }) // 设置到redux中供后续使用

        // 定位信息
        this.prcoessAddress(location)
      }
    }).catch(err => console.log(err))
  }

  reverseGeocoder({ latitude, longitude }) {
    return new Promise((resolve, reject) => {
      qqmapsdk.reverseGeocoder({
        location: { latitude, longitude },
        success(res) {
          if (res.status !== 0) {
            reject(res.status)
          } else {
            resolve({
              address: res.result.address,
              formatted_addresses: res.result.formatted_addresses
            })
          }
        },
        fail() {
          reject()
        }
      })
    })
  }

  async prcoessAddress(loc) {
    let { latitude, longitude, address, name } = loc
    // 如果没有地址的name, 调用腾讯地图api获取
    if (!name) {
      const { address: _address, formatted_addresses } = await this.reverseGeocoder({ latitude, longitude })
      address = _address
      name = formatted_addresses.recommend
    }

    Taro.setStorageSync('userPinLocation', JSON.stringify({ latitude, longitude, address, name }))
    this.props.onGetUserMapPin({
      latitude, // 经度
      longitude, // 纬度
      address,
      name
    })
    // 发送请求获取推荐店铺
    return asyncGetRecommendedShop(this.props.user.token, loc.latitude, loc.longitude).then(({ data, status }) => {
      if (!status) {
        // 没有找到合适店铺的处理
        Taro.showToast({
          title: '抱歉没有合适您的水果店',
          icon: 'none'
        })
        setTimeout(() => {
          Taro.switchTab({ url: '/pages/index/index' })
        }, 1500)
        
      }
      //Taro.setStorageSync('shop_id', data.shop_id)

      //this.props.onGetShopID(data.shop_id)
      //this.initShop()
    })
  }

    // 确认参团
    /**
     * @param keep {boolean} 保留原有
     * */
    confirmGroupModal (keep) {
        // const {groupItem} = this.state
        const {num} = this.state
        const {token} = this.props.user
        const { group, id,user_group} = this.props.good
        Taro.showLoading({})
        asyncJoinGroup({
            token,
            product_id: id,
            product_group_id: group.id,
            parent_id: user_group[0].id,
            had_ok: keep
        }).then(({status, msg, data}) => {
            Taro.hideLoading()
           
            if (status) {
              // title: status ? '参团成功' : '参团失败',
                Taro.showToast({
                  title: '参团成功',
                  icon: 'none'
              })
                Taro.redirectTo({url: `/pages/cart/settle?type=2&num=${num}`}) // 表示来自结算页
            } else if (status==false && data.had_group){
                // 不成功
                Taro.showModal({
                    title: '提示',
                    content: msg,
                    cancelText: '不保留',
                    confirmText: '保留'
                })
                  .then(res => {
                      console.log(res.confirm, res.cancel)
                      if (res.confirm) {
                          this.confirmGroupModal(true)
                      }
                      if (res.cancel) {
                          asyncCancelGroup(token, data.group_code).then(() => {
                              this.confirmGroupModal(false)
                          })
                      }
                  })
            } else {
              Taro.showToast({
                title: msg,
                icon: 'none'
              })
              setTimeout(() => {
                Taro.switchTab({url: '/pages/index/index'})
              }, 1500)
            }
        }).catch(() => {
            Taro.hideLoading()
        })
    }
    onPosterSuccess (preview, e) {
        const { detail } = e;
        // 预览
        if (preview === 'poster') {
            Taro.previewImage({
                current: detail,
                urls: [detail]
            })
        }
        // 分享
        if (preview === 'share') {
            this.setState({
                shareImg: detail
            })
        }
    }
  componentDidShow () {
    const { token } = this.props.user
    if (!token) {
      this.setState({ showAuthModal: true })
      return
    }
    this.props.onAsyncDetail() // 加载商品详情
    this.props.onAsyncLoadOffer() // 加载推荐列表
    let scenevalue =this.$router.params.scene 
    this.props.onYncgroupDetail(scenevalue)
  }

  componentDidMount() {
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'SVRBZ-4TXW6-Y7ZSW-ELRLI-2FIWK-XYBQ3'
    });
  }

  componentDidHide () { }

  render () {
        const { showAuthModal } = this.state
        console.info('登陆框：'+showAuthModal)
        if(showAuthModal) {
          return (          
            <LoginModal
                  title='授权提示'
                  contentText='需要您登陆授权并允许获得您的位置信息，用以更好的为您推荐精选水果店铺'
                  onConfirmCallback={this.prcoessAuthResult.bind(this)}
             />           
            
          )
        }
        const { num} = this.state
        const {offerList} = this.props.cart
        const renderOfferList = offerList.map((item, index) => {
            return (
              <GoodItem
                key={index}
                goodId={item.id}
                thumb={item.thumb}
                name={item.name}
                tags={item.tags}
                sales={item.month_sale}
                price={item.sale_price}
                sale_price={item.sale_price}
                spec_name={item.spec.name}
                weight={item.weight}
                isGroup={item.type_id === 2}
                host='cart'
              />
            )
          })
        
        const {group,user_group,minutes, tags , point} = this.props.good
        if(group == undefined){
            return
        }
        const renderTags = tags.map((tag, index) => {
          return (<Text key={index} className='good-tag'>{tag.name}</Text>)
        })
        // 团成员列表
        const groupMembers = ((user_group) || []).map((member, index) => {
          return <View key={index} className='order-group-member'>
            <AtAvatar circle size='small' image={member.user.avatar} className='order-group-avatar' />
            <Text className='order-group-nick'>{member.user.nickname}</Text>
          </View>

        })

        return (
          <View className='show'>
           
            
            {/*头部倒计时*/}
            <View className='header'>
              <View className='title'>
                剩余时间
              </View>
               <count-down initDuration={minutes * 60} />
            </View>
            {/*商品列表*/}
            <View className='goods-box'>
              <View className='goods-img-box'>
                <Image src={this.props.good.thumb} />
              </View>
              {/* 商品名称 */}
              <View className='goods-info-box'>
                <View className='good-name'>
                  <Text>{this.props.good.name}</Text>
                </View>
                <View className='good-specifications'>
                {this.props.good.weight}g/{this.props.good.spec.name}
                </View>
                {/*标签*/}
                <View className='good-tags'>
                  {/* <Text className='good-tag'>进口</Text> */}
                  {renderTags}
                </View>
                
                {/* 价格*/}
                <View className='good-price'>
                  <Text className='now-price'>{parseFloat(group.group_price == "undefined"?'0':group.group_price / 100).toFixed(2)}</Text>
                  <View className='num'>
                    <NumberInput
                      min={1}
                      max={100}
                      step={1}
                      width={200}
                      value={num}
                      onChange={this.handleNumChange.bind(this)}
                    />
                  </View>

                </View>
              </View>
            </View>
             {/*团信息*/}
             {group && <View className='order-group'>
              <View className='order-group-members'>
                {groupMembers}
                {group && (group.group_num - group.joined_num > 0) && <View  className='order-group-member'>
                  <AtAvatar circle size='small' text='?' className='order-group-avatar' />
                  <Text className='order-group-nick'>还差<Text className='order-group-left'>{group.group_num - group.joined_num}</Text>人</Text>
                </View>}
              </View>
            </View>}
            <View className='section-header'>
                <Text className='name nameTitle'>推荐商品</Text>
            </View>
            <ScrollView className='section-list' scrollWithAnimation scrollX>
              <View className='at-row'>
                {renderOfferList}
              </View>
            </ScrollView>
            <View className='foot-height'>
              </View>
            {/*底部*/}
            <View className='good-bottom'>
              <View className='good-bottom-home' onClick={this.goHome.bind(this)}>
                <Image src={homeImg}  style='width: 20px;height: 20px;' />
                <View>首页</View>
              </View>
              <View className='good-bottom-join'>
                <Button onClick={this.confirmGroupModal.bind(this, false)} className='group-modal-btn'>参与拼团</Button>
              </View>
            </View>
          </View>
    )
    }
}

export default Show
